import React, { PropTypes, Component } from 'react';
import Table from './MyTable'
import Column from './Column'
import { myAjax, getAuthShop, ROOTURL_TABLE } from './../publicAPI/publicAPI';
import styles from './SimpleTable.css';

export default React.createClass({
  getInitialState: function() {
    let date = new Date();
    return {
      year: date.getFullYear(),
      month: date.getMonth() + 1,
      shopNames: [],
      shopForTypes: [],
      shopSelect: '请选择门店',
      typeSelect: '请选择服务类型',
      tData: [{}],
      processData: [{}],
      selectedShopData: [{}],
    };
  },
  componentWillMount: function() {
    let _this = this;

    myAjax(ROOTURL_TABLE + 'cafune/servant/sermondailystdata.api', 'POST', { year:this.state.year, month:this.state.month }, function(data) {
      //console.log(data);
      this.setState({
        processData: data,
      });
    }.bind(_this), function(err) {});
  },
  componentDidMount: function() {
    let _this = this;
    //配合权限
    //console.log('DidMount执行');
    getAuthShop(null, function(data) {
      var shopsForAdm = [];
      data.forEach((shopMes) => {
        shopsForAdm.push(shopMes.dname);
      }); 
      this.setState({
        shopsForAdm: shopsForAdm,
        shopNames: shopsForAdm
      });
    }.bind(_this));
  },
  handleClick: function() {
		let yearSelect = parseInt(this.refs.yearSelect.value);
		let monthSelect = parseInt(this.refs.monthSelect.value);
    let shopSelect = this.state.shopSelect;
    let typeSelect = this.state.typeSelect;
    if(!yearSelect || !(/^2\d{3}$/.test(yearSelect))) {
      alert("内容不能为空或格式错误");
      this.refs.yearSelect.focus();
      return
    }
    if(!monthSelect || !(/^0?[1-9]{1}$|^1[0-2]$/.test(monthSelect))) {
      alert("内容不能为空或格式错误");
      this.refs.monthSelect.focus();
      return
    }
    if (shopSelect == '请选择门店') {alert('商店与服务类型选择不能为空'); return};
    if (typeSelect == '请选择服务类型') {alert('商店与服务类型选择不能为空'); return};
		
    let _this = this;
		myAjax(ROOTURL_TABLE + 'cafune/servant/sermondailystdata.api', 'POST', {year: yearSelect, month: monthSelect}, function(data) {
      //console.log(data);
      let shopNameArray = this.state.shopsForAdm;
      let ids = data.servantIds;
      let selectedShopData = [];

      for (let i in ids) {
        let id = ids[i];   
        if (data[id].servantShop == shopSelect) {
          selectedShopData.push(data[id]);
        }
      }
      let tData = [];
      selectedShopData.forEach((data) => {
        let a = {'servantName': data.servantName, 'servantShop': data.servantShop};
        let b = data.dailyServeTypeCount[`${typeSelect}`];
        Object.assign(a, b);
        tData.push(a);
      });

      this.setState({
        tData: tData,
        year: yearSelect,
        month: monthSelect,
      });
      console.log(tData);
		}.bind(_this), function(err) {alert("获取服务器内容失败");});
	},
  onChange: function() {
    let shopSelect = this.refs.shopSelect.value;
    let shopNameArray = this.state.shopNameArray;
    let processData = this.state.processData;
    let ids = processData.servantIds;
    let selectedShopData = [];

    if(shopSelect == '请选择门店')  return;

    for (let i in ids) {
      let id = ids[i];
      if (processData[id].servantShop == shopSelect) {
        selectedShopData.push(processData[id]);
      }
    }

    let shopForTypes = this.state.processData.shopForTypes[`${shopSelect}`];
    this.setState({
      shopSelect: shopSelect,
      shopForTypes: shopForTypes,
      selectedShopData: selectedShopData,
    }); 
  },
  onChange2: function() {
    let typeSelect = this.refs.typeSelect.value;
    let selectedShopData = this.state.selectedShopData;
    let processData = this.state.processData;
    let shopNameArray = this.state.shopNameArray;

    if(typeSelect == '请选择服务类型')  return;

    let tData = [];
    selectedShopData.forEach((data) => {
      let a = {'servantName': data.servantName, 'servantShop': data.servantShop};
      let b = data.dailyServeTypeCount[`${typeSelect}`];
      Object.assign(a, b);
      tData.push(a);
    });
    console.log(tData);

    this.setState({
      typeSelect: typeSelect,
      tData: tData,
    });
  },
  handleKeyPress: function(e) {
    if(e.which == 13) {
      this.handleClick();
    }
  },
  render: function() {
    return (
      <div>
      	<div>
        <form>
          <select ref="shopSelect" onChange={this.onChange} className={styles['select']}>
            <option value="请选择门店">请选择商店</option>
            {
              this.state.shopNames.map((name) => {
                return (
                  <option value={name} key={name}>{name}</option>
                );
              })
            }
          </select>
          <select ref="typeSelect" onChange={this.onChange2} className={styles['select']}>
            <option value="请选择服务类型">请选择服务类型</option>
            {
              this.state.shopForTypes.map((name) => {
                return (
                  <option value={name} key={name}>{name}</option>
                );
              })
            }
          </select>
      		<label >
      			<input ref="yearSelect" onKeyPress={this.handleKeyPress} className={styles.input} placeholder="如：2016" />年
      			<span>&nbsp;&nbsp;</span><input ref="monthSelect" onKeyPress={this.handleKeyPress} className={styles.input} placeholder="如：3" />月
      		</label>
			    <button type="button" onClick={this.handleClick} onKeyPress={this.handleKeyPress} className={styles.button}>确定</button>
      	</form>
        </div>
        <span>{`${this.state.shopSelect} - ${this.state.typeSelect} - ${this.state.year}-${this.state.month}`}</span>
        <Table data={this.state.tData} className={styles.container}>
          <Column dataKey='servantName' name='理发师' width="120px" order="false" key={`col-servantName`}/>
          <Column dataKey='servantShop' name='所属门店' width="120px" order="false" key={`col-servantShop`}/>
          {
            (this.state.tData == 0)? '' : Object.keys(this.state.tData[0]).map(entry => {
              if(/\d/.test(entry)) {
                return <Column dataKey={entry} name={entry} key={`col-${entry}`}/>
              }              
            })
          }
        </Table>
      </div>
    );
  }
});


